<template>
  <div class="sku-box">
    <div v-show="step === 0">
      <div v-for="(key, keyIndex) in keyList" :key="key.id">
        <span
          :class="key.children && key.children.length === 0 ? 'disabled' : ''"
        >
          {{ key.attributeName }}
        </span>
        <div class="check-list">
          <span
            v-for="(value, valueIndex) in key.children"
            :key="key.id + ' ' + value.id"
            :class="value.checked ? 'checked' : 'check-item1'"
            @click="checkedValue(keyIndex, valueIndex)"
          >
            {{ value.attributeValue }}
          </span>
        </div>
      </div>
    </div>
    <!-- 组合按钮 -->
    <el-button @click="submitGroupSku" v-show="step === 0" type="primary">
      确定SKU
    </el-button>
    <div v-show="step === 1">
      <table>
        <tr>
          <th>序号</th>
          <th>sku</th>
          <th>sku信息</th>
          <th>状态</th>
          <th>进货价</th>
          <th>销售价</th>
          <th>赠送倍数</th>
        </tr>
        <tr v-for="(sku, index) in skuList" :key="sku.specificationName">
          <td>{{ index + 1 }}</td>
          <td>{{ sku.show }}</td>
          <td>{{ sku.specificationName }}</td>
          <td>{{ sku.status === 1 ? "上架中" : "已下架" }}</td>
          <td style="width: 100px">
            <el-input v-model="sku.price"></el-input>
          </td>
          <td style="width: 100px">
            <el-input v-model="sku.vipPrice"></el-input>
          </td>
          <td style="width: 100px">
            <el-select v-model="sku.giftAmount" filterable placeholder="请选择">
              <el-option :label="0" :value="0"> </el-option>
              <el-option :label="1" :value="1"> </el-option>
              <el-option :label="2" :value="2"> </el-option>
              <el-option :label="3" :value="3"> </el-option>
            </el-select>
          </td>
        </tr>
      </table>
    </div>
    <el-button @click="submitSku" v-show="step === 1" type="primary">
      确定SKU
    </el-button>
    <el-button @click="backChoice" v-show="step === 1" type="primary"
      >重选sku</el-button
    >
    <el-button @click="backList" v-show="step === 0" type="primary"
      >取消重选sku</el-button
    >
  </div>
</template>
<script>
import { valueList, keyList, addSku, skuDetail } from "@/api/ds/sku";

export default {
  components: {},
  props: {
    price: {
      type: Number,
      default: 0,
    },
    vipPrice: {
      type: Number,
      default: 0,
    },
    giftAmount: {
      type: Number,
      default: 0,
    },
    size: {
      type: String,
      default: "",
    },
  },
  data() {
    return {
      step: 0,
      keyList: [],
      skuList: [],
    };
  },
  computed: {},
  watch: {
    size(newVal) {
      // 健康功能
      // 野谷
      // 衢州
      console.log("size,变化");
      if (newVal) {
        this.init(newVal);
      }
    },
  },
  created() {
    this.getKeyValueList();
  },
  methods: {
    initStep() {
      console.log("initStep");
      this.step = 0;
      this.keyList = [];
      this.skuList = [];
      this.getKeyValueList();
    },
    async init(size) {
      console.log("init");

      let sizeIds = size.split(",");
      //   根据sku id获取使用的key,value
      let promiseList = sizeIds.map((sizeId) => {
        return new Promise(async (resolve, reject) => {
          let res = await skuDetail({ id: sizeId });
          if (res.code === 200) {
            resolve(res.data);
          } else {
            reject();
          }
        });
      });

      let resList = await Promise.all(promiseList);
      this.skuList = resList.map((item) => {
        item.show = item.specificationName;
        return item;
      });

      let valueList = [];
      resList.map((item) => {
        let kvList = item.specificationName.split(";");
        let arr = kvList.map((kv) => {
          return kv.split(":")[1];
        });
        valueList = valueList.concat(arr);
      });

      valueList = Array.from(new Set(valueList));

      //   valueList 的每一项设置激活
      valueList.map((id) => {
        this.keyList.forEach((key) => {
          if (key.children) {
            key.children.forEach((value) => {
              if (value.id == id) {
                //   value.checked = true;
                this.$set(value, "checked", true);
              }
            });
          }
        });
      });

      this.$forceUpdate();
      this.step = 1;
    },
    async getKeyValueList() {
      let res = await keyList();
      if (res.code === 200) {
        this.keyList = res.rows;
      }

      let promiseList = this.keyList.map((key) => {
        return new Promise(async (resolve, reject) => {
          let res = await valueList({ kid: key.id });
          if (res.code === 200) {
            resolve(res.rows);
          } else {
            reject("error");
          }
        });
      });

      let resList = await Promise.all(promiseList);

      this.keyList.forEach((key) => {
        this.$set(key, "children", []);
        resList.map((value) => {
          if (value.length !== 0) {
            if (key.id === value[0].kid) {
              key.children = value;
            }
          }
        });
      });

      this.keyList.forEach((key) => {
        key.children.forEach((value) => {
          value.checked = false;
        });
      });
    },
    /**
     * 选中key
     */
    submitKeyChoice() {
      this.keyChoiceShow = false;
    },

    checkedValue(keyIndex, valueIndex) {
      // 判断是否已经有两个key被选中了
      let beCheckedKeyNum = 0;
      let checkedKeyIdArr = [];
      this.keyList.map((key) => {
        let isChecked = false;
        if (key.children) {
          key.children.map((value) => {
            if (value.checked) {
              isChecked = true;
            }
          });
        }

        if (isChecked) {
          beCheckedKeyNum = beCheckedKeyNum + 1;

          checkedKeyIdArr.push(key.id);
        }
      });

      if (beCheckedKeyNum === 2) {
        // 判断现在点击的是否是已经点击过的
        if (checkedKeyIdArr.includes(this.keyList[keyIndex].id)) {
          this.keyList[keyIndex].children[valueIndex].checked =
            !this.keyList[keyIndex].children[valueIndex].checked;
          this.$forceUpdate();
        } else {
          this.$message({
            showClose: true,
            message: "最多选择2个key",
            type: "warning",
          });
        }
      } else if (beCheckedKeyNum > 2) {
        this.$message({
          showClose: true,
          message: "最多选择2个key",
          type: "warning",
        });
      } else {
        this.keyList[keyIndex].children[valueIndex].checked =
          !this.keyList[keyIndex].children[valueIndex].checked;
        this.$forceUpdate();
      }
    },
    /**
     * 提交服务器
     */
    async submitSku() {
      let promiseList = this.skuList.map((sku) => {
        return new Promise(async (resolve, reject) => {
          let show = sku.show;
          delete sku.show;
          let res = await addSku(sku);
          if (res.code === 200) {
            this.$notify({
              title: "成功",
              message: `${show} ${res.msg}`,
              type: "success",
            });

            resolve(res.data);
          } else {
            reject();
          }
        });
      });

      let resList = await Promise.all(promiseList);

      this.$emit("submit", resList);
    },
    backChoice() {
      this.step = 0;
    },
    backList() {
      this.step = 1;
    },
    /**
     * 本地组合sku
     */
    submitGroupSku() {
      // 取出选中的sku
      let checkedKeyList = JSON.parse(
        JSON.stringify(
          this.keyList.filter((key) => {
            if (key.children) {
              let arr = key.children.filter((value) => {
                return value.checked;
              });

              if (arr.length > 0) {
                return true;
              }
            } else {
              return false;
            }
          })
        )
      );

      // 剔除未选中value值
      checkedKeyList.forEach((key) => {
        key.children = key.children.filter((value) => {
          return value.checked;
        });
      });

      let skuList = [];

      // 组合
      if (checkedKeyList.length === 2) {
        let key0 = checkedKeyList[0];
        let key1 = checkedKeyList[1];

        key0.children.map((value1) => {
          key1.children.map((value2) => {
            let sku = {
              specificationName: `${key0.id}:${value1.id};${key1.id}:${value2.id}`,
              status: 1,
              price: this.price,
              vipPrice: this.vipPrice,
              giftAmount: this.giftAmount,
              show: `${value1.attributeValue} ${value2.attributeValue}`,
            };

            skuList.push(sku);
          });
        });
      } else {
        let key = checkedKeyList[0];
        key.children.map((value) => {
          let sku = {
            specificationName: `${key.id}:${value.id}`,
            status: 1,
            price: this.price,
            vipPrice: this.vipPrice,
            giftAmount: this.giftAmount,
            show: `${value.attributeValue}`,
          };

          skuList.push(sku);
        });
      }

      this.skuList = skuList;
      this.$forceUpdate();
      this.step = 1;
    },
  },
  mounted() {},
  beforeCreate() {},
  beforeMount() {},
  beforeUpdate() {},
  updated() {},
  beforeDestroy() {},
  destroyed() {},
  activated() {},
  deactivated() {},
};
</script>
<style lang="scss" scoped>
table,
th,
td {
  border: 1px solid black;
  text-align: center;
  vertical-align: center;
}

tr:hover {
  background-color: #f5f5f5;
}

table {
  width: 100%;
  border-collapse: collapse;
  height: 50px;
  margin-bottom: 15px;
}

.sku-box {
  width: 100%;
  min-height: 100px;
  color: #333333;
}
.disabled {
  color: #999999;
  text-decoration: line-through;
}

.check-list {
  width: 100%;
  display: flex;
  flex-flow: row nowrap;
  justify-content: flex-start;
  align-items: center;

  .check-item1 {
    width: 100px;
    height: 30px;
    border: 1px solid #cccccc;
    color: #333333;
    text-align: center;
    margin: 5px;
    border-radius: 5px;

    font-size: 10px;
    line-height: 30px;
  }

  .checked {
    width: 100px;
    height: 30px;
    border: 1px solid #ff0000;
    color: #333333;
    text-align: center;
    margin: 5px;
    border-radius: 5px;

    font-size: 10px;
    line-height: 30px;
  }
}
</style>
